import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import { DatePicker } from 'antd';
import moment from 'moment';
import './index.less';

export default (props) => {
  const { RangePicker } = DatePicker;
  const [dates, setDates] = useState(null);
  const {
    startTime = 'statisticsDateStart',
    endTime = 'statisticsDateEnd',
    datePicketProps = {},
    defaultList,
    onChange,
  } = props;
  const disabledDate = (current) => {
    if (!dates) {
      return false;
    }
    let tooLate =
      current <= moment().subtract(30, 'days') || current > moment(new Date()).subtract(1, 'days');

    return !!tooLate;
  };
  const onOpenChange = (open) => {
    if (open) {
      setDates([null, null]);
    } else {
      setDates(null);
    }
  };
  const [list, setList] = useState(defaultList ? defaultList : [
    { label: '昨日发布', value: 'yesterday' },
    { label: '7日内发布', value: 'last7' },
    { label: '30天内发布', value: 'last30' },
  ]);
  const [data, setData] = useState({
    dateType: 'yesterday',
  });
  useEffect(() => {
    onChange&&onChange(data);
  }, [data]);
  return (
    <div className="DateSelect_box">
      {list.map((item, index) => {
        return (
          <div
            key={index}
            onClick={() => {
              if (item.value !== data.dateType) {
                setData({
                  dateType: item.value,
                  [startTime]: '',
                  [endTime]: '',
                });
              }
            }}
            className={
              item.value === data.dateType
                ? 'DateSelect_box_btn DateSelect_box_select'
                : 'DateSelect_box_btn DateSelect_box_noSelect'
            }
          >
            {item.label}
          </div>
        );
      })}
      <div className="DateSelect_date">
        <RangePicker
          disabledDate={disabledDate}
          onCalendarChange={(val) => setDates(val)}
          onOpenChange={onOpenChange}
          onChange={(e) => {
            if (e === null) {
              setData({
                dateType: list[0].value,
                [startTime]: '',
                [endTime]: '',
              });
            } else {
              setData({
                [startTime]: moment(e[0]).format('YYYY-MM-DD'),
                [endTime]: moment(e[1]).format('YYYY-MM-DD'),
              });
            }
          }}
          {...datePicketProps}
        ></RangePicker>
      </div>
    </div>
  );
};
